package main

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	"github.com/patrickmn/go-cache"
	"gorm.io/gorm"
	"time"
)

func doVoteImp(v DoVote, db *gorm.DB, cache *cache.Cache) *Result {
	l, hasFind := checkToken(v.Token, cache)
	if !hasFind {
		return &Result{
			Code: 402,
			Data: "Token已失效，请重新登陆",
		}
	}
	vote := getVoteById(v.Id, db)
	if vote == nil {
		return &Result{
			Code: 400,
			Data: "数据错误",
		}
	}
	now := time.Now().Unix()
	if vote.BeginTime > now || vote.EndTime < now {
		return &Result{
			Code: 400,
			Data: "不在可投票时间内!",
		}
	}
	// 获取候选人
	voter := vote.Voters[v.VoterId]
	if voter.Id != "" {
		if vote.VotedUser[l.Username] >= 1 {
			return &Result{
				Code: 400,
				Data: "您已进行过投票！",
			}
		}
		voter.Numbers += 1
		vote.Voters[v.VoterId] = voter
		vote.VotedUser[l.Username] += 1
	} else {
		return &Result{
			Code: 400,
			Data: "参数错误！",
		}
	}
	err := updateVote(*vote, db)
	if err != nil {
		return &Result{
			Code: 400,
			Data: err.Error(),
		}
	} else {
		return &Result{
			Code: 200,
			Data: "投票成功！",
		}
	}
}

func getVoteImp(ID string, db *gorm.DB) *Result {
	res, _ := json.Marshal(getVoteById(ID, db))
	return &Result{
		Code: 200,
		Data: string(res),
	}
}

func getAllVoteImp(token string, db *gorm.DB, cache *cache.Cache) *Result {
	l, hasFind := checkToken(token, cache)
	if !hasFind {
		return &Result{
			Code: 402,
			Data: "Token无效，请重新登陆",
		}
	} else {
		res, _ := json.Marshal(getAllVote(l.OrgId, db))
		return &Result{
			Code: 200,
			Data: string(res),
		}
	}
}

func createVoteImp(token string, v Vote, db *gorm.DB, cache *cache.Cache) *Result {
	l, hasFind := checkToken(token, cache)
	if !hasFind {
		return &Result{
			Code: 402,
			Data: "token已失效，请重新登陆",
		}
	}
	if !l.IsAdmin {
		return &Result{
			Code: 401,
			Data: "用户无权限！",
		}
	}
	v.OrgId = l.OrgId
	// 生成一项投票的ID
	b := md5.Sum([]byte(v.OrgId + v.Name))
	v.Id = fmt.Sprintf("%x", b[:])

	v.VotedUser = make(map[string]int)
	v.VotedUser["-1"] = 0
	err := createVote(v, db)
	if err != nil {
		return &Result{
			Code: 400,
			Data: err.Error(),
		}
	}
	return &Result{
		Code: 200,
		Data: "创建投票成功",
	}
}
